package com.suxin.netty.protocol;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author Tang
 * @classname MyServer
 * @description [ TODO ]
 * @date 2021/1/11 13:23
 */
public class MyServer {

    public static void main(String[] args) throws Exception{
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup(4);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap // 设置两个线程组
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            System.out.println("hashCode:--->" + socketChannel.hashCode());
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new MySimpleDecoder());
                            pipeline.addLast(new MySimpleServerHandler());

                            pipeline.addLast(new MySimpleEncoder());
                        }
                    });
            System.out.println("...服务器 is ready ...");
            ChannelFuture future = bootstrap.bind(9000).sync();
            // 对关闭通道进行监听
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

}